package com.huateng.web.servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huateng.util.DateUtil;
import com.huateng.util.IPUtils;

@WebServlet("/DataCollServlet")
public class DataCollServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String mapFilePath = DataCollServlet.class.getClassLoader().getResource("").getPath() + "map.dat";
	private static String dataCollectOutputDir = ReadConfigureFile.getInstance().createFileDir("DataCollectOutputDir");
	private static String actionDataFilePre = "ActionData";
	private static String regDataFilePre = "RegData";
	private static String fileSuf = ".dat";
	private static String fieldSplitChar = "@";

	public DataCollServlet() {
		super();
		// TODO Auto-generated constructor stub
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, String> map = new HashMap<String, String>();
		String params = request.getParameter("params");
//		params = new String(params.getBytes("ISO-8859-1"), "UTF-8");
		map.put("params", params);

		String[] array = new String[10];// setCustomer中的字段
		String[] str = new String[13];// 通过str拼接最后字符串
		// 访客id
		// 如果用户登录了且session没有过期，会在jsp中获取到访客id，如果浏览器清空session，游客登录str[0] = "";
		try {
			str[0] = decorateStr(decorateUserStr(params));// str[0]为第一个字段，即用户id
			if (str[0].equals(fieldSplitChar)) {
				str[0] = "null";
			} else {
				array = str[0].split(fieldSplitChar);
				str[0] = array[0];// array即setCustomer中的第一个值
			}
		} catch (Exception e) {
			str[0] = "null";
		}

		// 终端ip
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		str[1] = ip;

		// 会话id
		String sessionId = request.getSession().getId();
		if (sessionId != null) {
			str[2] = sessionId;
		} else {
			str[2] = "null";
		}

		// cookies
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			str[3] = "null";
		} else {
			str[3] = "";
			for (int k = 0; k < cookies.length; k++) {
				str[3] += cookies[k].getName() + ":" + cookies[k].getValue() + ",";
			}
			str[3] = str[3].substring(0, str[3].length() - 1);
		}
		// 当前页面名称
		Map<String, String> mapPage = splitStr(params);
		// String utmp = mapPage.get("utmp");
		String utmdt = mapPage.get("utmdt");
		// str[5] = utmdt+"|@|"+utmp;
		str[4] = utmdt;

		// url
		str[5] = request.getHeader("Referer");

		// 页面访问时间
		Map<String, String> mapTemp = splitStr(params);
		String utmcc = mapTemp.get("utmcc");
		int indexf = utmcc.indexOf(";");
		int indexd = utmcc.indexOf("=");
		String strTemp = utmcc.substring(indexd + 1, indexf);
		String[] timeArray = strTemp.split("\\.");
		if (timeArray.length > 4) {
			str[6] = timeArray[4] + "000";

			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(Long.parseLong(str[6]));

			Date date = calendar.getTime();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			str[6] = sf.format(date);
		}

		// 停留时间
		str[7] = "null";

		// 源url
		try {
			if (array[1] == null) {
				str[8] = "null";
			} else {
				str[8] = URLDecoder.decode(array[1]);// setCustomer的第一个字段
			}
		} catch (Exception e) {
			str[8] = "null";
		}

		// 页面返回状态
		String referer = request.getHeader("Referer");
		if (referer == null || "".equals(referer)) {
			str[9] = "";
		} else {
			// URL url = new URL(referer);
			// URLConnection rulConnection = url.openConnection();
			// HttpURLConnection httpUrlConnection = (HttpURLConnection)
			// rulConnection;
			// httpUrlConnection.setConnectTimeout(300000);
			// httpUrlConnection.setReadTimeout(300000);
			// httpUrlConnection.connect();
			// String code = new
			// Integer(httpUrlConnection.getResponseCode()).toString();
			// str[9] = code;
			str[9] = null;
		}
		System.out.println("str[9]: " + str[9]);

		// 产品id，产品
		str[10] = decorateStr(decorateUserStr(params));
		if (str[10] == null) {
			str[10] = "null";
		} else {
			int count = 0;
			str[10] = "";
			for (int i = 0; i < array.length; i++) {
				if (array[i] != null) {
					count += 1;
				}
			}
			if (count > 2) {
				for (int i = 2; i < count; i++) {
					if (array[i] != null) {
						str[10] += (array[i] + "@");
					}
				}
				str[10] = str[10].substring(0, str[10].length() - 1);
			} else {
				str[10] = "null";
			}
		}
		str[11] = "null";

		IPUtils.load(mapFilePath);
		String[] provinces = IPUtils.find(ip);
		if (provinces != null && provinces.length > 2) {
			String province = provinces[1];
			if (province != null && province.length() > 0) {
				str[12] = province;
			}
		} else {
			str[12] = "null";
		}

		StringBuffer finalStr = new StringBuffer("");
		for (int i = 0; i < str.length; i++) {
			finalStr.append(str[i]);
			if (i < (str.length -1))
				finalStr.append(fieldSplitChar);
		}
		writeToFile(actionDataFilePre, finalStr.toString());

		String otherStr = "";
		if (str.length > 6) {
			String ipclient = str[1];
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			String time = sf.format(new Date());
			String title = str[4];
			otherStr = ipclient + fieldSplitChar + time + fieldSplitChar + title + fieldSplitChar + "1";
			// if(title.equals("信用卡中心")){
			// otherStr = ipclient+"@"+time+"@"+title+"@"+"1";
			// }else if(title.equals("用户注册")){
			// otherStr = ipclient+"@"+time+"@"+title+"@"+"2";
			// }else if(title.equals("注册成功")){
			// otherStr = ipclient+"@"+time+"@"+title+"@"+"3";
			// }
		}
		writeToFile(regDataFilePre, otherStr);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public static String decorateItem(String param) {
		int index = param.indexOf("item");
		int tail = param.indexOf("utmac");
		String str = param.substring(index + 5, tail - 1);
		String str1 = decorateStr(str);
		return str1;

	}

	// 获取setCustomer方法中第二个括号内的数据
	public static String decorateUserStr(String param) {
		Map<String, String> mapOne = splitStr(param);
		String str = "";
		try {
			String utme = mapOne.get("utme");
			String[] arr = utme.split("\\)");
			String str1 = arr[arr.length - 2];
			int len = str1.indexOf("(");
			str = str1.substring(len + 1, str1.length());
		} catch (Exception e) {
			str = "";
		}
		return str;
	}

	public static void writeToFile(String filePre, String content) {
		boolean flag = true;
		String path = dataCollectOutputDir + filePre + "_" + DateUtil.getCurrentDate() + fileSuf;
		File file = new File(path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		if (!file.exists()) {
			try {
				file.createNewFile();
				flag = false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 写入文件
		try {
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path, true),"UTF-8");
//			BufferedWriter writer = new BufferedWriter(new FileWriter(osw, true));
			BufferedWriter writer = new BufferedWriter(osw);
			if (flag)
				writer.newLine();
			writer.write(content);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 处理setCustomer方法设置的值
	public static String decorateStr(String str) {
		if (str.contains("^")) {
			String tempStr = "";
			String finStr = "";
			String sp = "\\^";
			String[] array = str.split(sp);
			for (int i = 0; i < array.length; i++) {
				int num = array[i].indexOf("=");
				tempStr = array[i].substring(num + 1, array[i].length());
				if (tempStr.contains("=")) {
					String[] arr = tempStr.split(";");
					tempStr = "";
					for (int k = 0; k < arr.length; k++) {
						int len = arr[k].indexOf("=");
						tempStr += arr[k].substring(len + 1, arr[k].length()) + fieldSplitChar;
					}
				}
				finStr += tempStr + fieldSplitChar;
			}
			return finStr;
		} else if (str.contains("*")) {
			String[] arr = str.split("\\*");
			String finalStr = "";
			for (int i = 0; i < arr.length; i++) {

				finalStr += arr[i] + fieldSplitChar;
			}
			return finalStr.substring(0, finalStr.length() - 1);
		} else {
			return str + fieldSplitChar;
		}
	}

	public static Map splitStr(String param) {
		Map<String, String> submap = new HashMap<String, String>();
		int num = 0;
		String sp = "\\^";
		String[] str;
		String[] array = param.split(sp);
		for (int i = 0; i < array.length; i++) {
			num = array[i].indexOf("=");
			if (num >= 0)
				submap.put(array[i].substring(0, num), array[i].substring(num + 1, array[i].length()));
		}
		return submap;
	}
}
